package SingleMachineArrangeImpl;

import java.util.Arrays;

//最早交货期优先（有就绪时间、允许中断）
public class EDDx extends SingleMachineArrange{
    //判断当前工件是否加工完成
    private boolean OnComplete(int[] process, int art){
        return process[art]==0;
    }
    private boolean OnAllComplete(int[] process){
        for (int i : process) {
            if(i>0) return false;
        }
        return true;
    }
    //找出要加工的(就绪)工件的下标
    private int OnReady(int [] ready, int [] process, int[] due, int t, int art){
        //要在就绪工件中找到最早交付的
        int mdue = Integer.MAX_VALUE;
        int imdue= art;
        for(int i=0;i< ready.length;i++){
            //尚未就绪或已完工
            if(ready[i] > t || process[i]<=0) continue;
            if(mdue > due[i]){
                mdue = due[i];
                imdue = i;
            }
        }
        return imdue;
    }

    public int getTime(int[] process,int[] ready,int[] due){
        if(process==null||ready==null||due==null){
            process = new int[]{4, 2, 6, 5};
            ready = new int[]{0, 1, 3, 5};
            due = new int[]{8, 12, 11, 10};
        }
        int n = process.length;
        int[] complete = new int[n];
        for(int i=0;i<n;i++) complete[i] = -1;
        //当前时间
        int t;
        //当前加工的工件
        int artifact = -1;
        for (t=0; !OnAllComplete(process); t++){
            System.out.print("当前时间： " + t + "\t");
            int tmp = artifact;
            //取得当前应加工的工件
            artifact = OnReady(ready,process,due,t,artifact);
            if(artifact==-1) {
                System.out.println();
                continue;
            }
            if(tmp!=artifact) System.out.print("工件" + (artifact+1) + "已就绪 ");
            //加工工件
            process[artifact]--;
            //检测是否完工
            if(OnComplete(process,artifact)){
                complete[artifact] = t + 1;
                System.out.print("工件" + (artifact+1) + "将在 t=" + complete[artifact] + "时完工 ");
            }
            System.out.println("正在加工工件" + (artifact + 1) );
        }
        System.out.println("工件完工时间：" + Arrays.toString(complete));
        return t;
    }
    @Override
    public void solve() {
        getTime(process, ready, due);
    }
}
